package com.example.newsmanager.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.newsmanager.dao.CommentMapper;
import com.example.newsmanager.entity.Comment;
import com.example.newsmanager.entity.DTO.CommentDTO;
import com.example.newsmanager.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {
    @Autowired
    private CommentMapper commentMapper;

    @Override
    public List<Comment> getCommentByParentId(Long parentId) {
        QueryWrapper<Comment> queryWrapper =new QueryWrapper<>();
        queryWrapper.eq("parent_id",parentId);
        return commentMapper.selectList(queryWrapper);
    }

    @Override
    public void addComment(Comment comment) {
        Date date =new Date();
        comment.setCommentTime(date);
        commentMapper.insert(comment);
    }

    @Override
    public Comment getById(Long id) {
        return commentMapper.selectById(id);
    }

    @Override
    public List<Comment> getList() {
        QueryWrapper<Comment> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(Comment::getParentId,0);
        return commentMapper.selectList(queryWrapper);
    }

    @Override
    public void setChildren(CommentDTO commentDTO) {
        List<CommentDTO> children = commentMapper.findByParentId(commentDTO.getCommentId());
        if(!children.isEmpty()){
            commentDTO.setChildren(children);
            children.forEach(this::setChildren);
        }
    }

    @Override
    public void setChildrenByNews(CommentDTO commentDTO){
        List<CommentDTO> children = commentMapper.findByNewsId(commentDTO.getCommentId(),commentDTO.getNewsId());
        if(!children.isEmpty()){
            commentDTO.setChildren(children);
            children.forEach(this::setChildrenByNews);
        }
    }

    @Override
    public List<CommentDTO> getAllComments() {
        List<CommentDTO> rootComments = commentMapper.findByParentId(0L);
        rootComments.forEach(this::setChildren);
        return rootComments;
    }
    @Override
    public List<CommentDTO> getAllCommentsByNewsId(Long id){
        List<CommentDTO> rootComments = commentMapper.findByNewsId(0L,id);
        rootComments.forEach(this::setChildrenByNews);
        return rootComments;
    }
    @Override
    public void deleteComment(Long id){
        commentMapper.deleteById(id);
    }
}
